package com.jojo.android.zxlib.base;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import java.util.List;

/**
 * @Author ZXW
 * @Date 2020/7/9 10:45
 **/
public abstract class BaseRecyclerAdapter<VH extends RecyclerView.ViewHolder, DATA> extends RecyclerView.Adapter<VH> {
    protected Context context;
    protected List<DATA> data;
    protected DATA entity;
    protected ItemClickListener<DATA> itemClickListener;

    public BaseRecyclerAdapter(Context context) {
        this.context = context;
    }

    public void setData(List<DATA> data) {
        this.data = data;
    }

    public List<DATA> getData() {
        return data;
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(getLayoutId(), parent, false);
        return getHolder(view);
    }


    @Override
    public int getItemCount() {
        if (data == null) return 0;
        return data.size();
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position, @NonNull List<Object> payloads) {
        try {
            final DATA o;
            final int index = position;
            if (data != null && data.size() > position) {
                entity = data.get(position);
                o = data.get(position);
            } else {
                o = null;
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        itemClickListener.onItemClick(index, o);
                    }
                }
            });
            super.onBindViewHolder(holder, position, payloads);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void setOnItemClick(ItemClickListener<DATA> itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    protected abstract VH getHolder(View v);

    /**
     * 布局ID
     *
     * @return
     */
    protected abstract int getLayoutId();


    public interface ItemClickListener<DATA> {
        void onItemClick(int index, DATA data);

        void onViewClick(View view, String msg, int index, DATA data);
    }

}
